import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tool } from '../tools/entities/tool.entity';
import { User } from '../users/entities/user.entity';
import { Review } from '../reviews/entities/review.entity';
import { Order } from '../orders/entities/order.entity';

/**
 * 统计数据服务
 */
@Injectable()
export class StatsService {
  constructor(
    @InjectRepository(Tool)
    private toolsRepository: Repository<Tool>,
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    @InjectRepository(Review)
    private reviewsRepository: Repository<Review>,
    @InjectRepository(Order)
    private ordersRepository: Repository<Order>,
  ) {}

  /**
   * 获取总体统计数据
   */
  async getOverview() {
    const [
      totalTools,
      totalUsers,
      totalReviews,
      totalOrders,
      totalViews,
      todayViews,
    ] = await Promise.all([
      this.toolsRepository.count(),
      this.usersRepository.count(),
      this.reviewsRepository.count(),
      this.ordersRepository.count(),
      this.getTotalViews(),
      this.getTodayViews(),
    ]);

    // 计算增长率（示例数据，实际应该查询历史数据）
    const viewsGrowth = todayViews > 0 ? 12.5 : 0;
    const usersGrowth = 8.3;
    const toolsGrowth = 5.2;

    return {
      totalTools,
      totalUsers,
      totalReviews,
      totalOrders,
      totalViews,
      todayViews,
      viewsGrowth,
      usersGrowth,
      toolsGrowth,
    };
  }

  /**
   * 获取访问趋势数据（最近7天）
   */
  async getTrends() {
    const days = 7;
    const trends = [];
    const now = new Date();

    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];

      // 这里应该从数据库查询实际数据
      // 目前使用模拟数据
      trends.push({
        date: dateStr,
        views: Math.floor(Math.random() * 1000) + 500,
        users: Math.floor(Math.random() * 100) + 50,
        tools: Math.floor(Math.random() * 10) + 5,
      });
    }

    return trends;
  }

  /**
   * 获取热门工具排行（TOP 10）
   */
  async getPopularTools() {
    const tools = await this.toolsRepository.find({
      order: {
        views: 'DESC',
      },
      take: 10,
      select: ['id', 'name', 'slug', 'logo', 'views', 'upvotes', 'rating'],
    });

    return tools;
  }

  /**
   * 获取最近活动
   */
  async getRecentActivities() {
    // 获取最近的评论
    const recentReviews = await this.reviewsRepository.find({
      relations: ['user', 'tool'],
      order: {
        createdAt: 'DESC',
      },
      take: 5,
    });

    // 获取最近的订单
    const recentOrders = await this.ordersRepository.find({
      relations: ['user'],
      order: {
        createdAt: 'DESC',
      },
      take: 5,
    });

    // 组合活动数据
    const activities = [
      ...recentReviews.map((review) => ({
        type: 'review',
        user: review.user.nickname,
        action: '评论了',
        target: review.tool.name,
        time: review.createdAt,
      })),
      ...recentOrders.map((order) => ({
        type: 'order',
        user: order.user.nickname,
        action: '购买了',
        target: order.planName,
        time: order.createdAt,
      })),
    ];

    // 按时间排序
    activities.sort((a, b) => b.time.getTime() - a.time.getTime());

    return activities.slice(0, 10);
  }

  /**
   * 获取总浏览量
   */
  private async getTotalViews(): Promise<number> {
    const result = await this.toolsRepository
      .createQueryBuilder('tool')
      .select('SUM(tool.views)', 'total')
      .getRawOne();

    return parseInt(result?.total || '0', 10);
  }

  /**
   * 获取今日浏览量（模拟数据）
   */
  private async getTodayViews(): Promise<number> {
    // 实际应该从访问日志表查询
    // 这里返回模拟数据
    return Math.floor(Math.random() * 500) + 200;
  }
}



